# -*- coding:utf-8 -*-
from django.db import models
from django.core import urlresolvers
from extra import ContentTypeRestrictedFileField
import os

class UniteFormation(models.Model):
    num_adm = models.IntegerField(unique=True)
    libelle = models.CharField(max_length=200)
    libelle_doc_8 = models.CharField(max_length=200, blank=True)
    code = models.CharField(max_length=20)
    niveau = models.CharField(max_length=6)
    type_uf = models.CharField("Type", max_length=6, blank=True)
    periodes = models.IntegerField(null=True, blank=True)
    app_doc_8 = models.DateField(null=True, blank=True)
    doc8 = ContentTypeRestrictedFileField(
        "Dossier pédagogique",
        upload_to='pdf/doc8',
        content_types = ['application/pdf','application/application.pdf',],
        max_upload_size = 5242880,
        blank = True,
        null = True,
        )
    doc8bis = ContentTypeRestrictedFileField(
        "Demande d'ouverture",
        upload_to='pdf/8bis',
        content_types = ['application/pdf','application/application.pdf',],
        max_upload_size = 5242880,
        blank = True,
        null = True,
        )
    app_8bis = models.DateField("Approbation ouverture", null=True, blank=True)
    num_8bis = models.CharField("Numéro d'ouverture", max_length=20, blank=True)
    transmis = ContentTypeRestrictedFileField(
        'Document "Transmis"',
        upload_to='pdf/transmis',
        content_types = ['application/pdf','application/application.pdf',],
        max_upload_size = 5242880,
        blank = True,
        null = True,
        )
    ap_dd = models.DateField("Adm. prov. (dépêche)", null=True, blank=True)
    ap_de = models.DateField("Adm. prov. (effet)", null=True, blank=True)
    ad_dd = models.DateField("Adm. déf. (dépêche)", null=True, blank=True)
    ad_de = models.DateField("Adm. déf. (effet)", null=True, blank=True)
    
    domaine = models.ForeignKey('DomaineFormation', verbose_name = 'Domaine de formation', null=True, blank=True)

    class Meta:
        verbose_name = "Unité de formation"
        verbose_name_plural = "Unités de formation"

    def doc8link(self):
        if self.doc8:
            return "<a href='%s'>%s</a>" % (self.doc8.url, self.code)
        else:
            return "%s" % (self.code,)
    doc8link.allow_tags = True
    doc8link.short_description = "Dossier pédagogique"
    doc8link.admin_order_field = "code"
    libelle
    
    def __unicode__(self):
        return "%s | %s" % (self.num_adm,self.libelle)
        
    def imprimer(self):
        path = os.path.join('/reports/uf/',str(self.id))
        lien = "<a href=%s>%s</a>" % (path,'pdf')
        return lien
    imprimer.allow_tags=True
    imprimer.short_description='Fiche'
    
    def inspecteur(self):
        return AttributionInspecteur.get_inspecteur_for_uf(self)

        
class OrganisationUf(models.Model):
    uf = models.ForeignKey('UniteFormation')
    num_org = models.IntegerField('N°')
    date_debut = models.DateField(blank=True, null=True)
    date_fin = models.DateField(blank=True, null=True)
    annee_scolaire = models.CharField("Année", max_length = 5)
    statut = models.CharField(max_length=10)
    da_faite = models.BooleanField("Dem. OK", default=False)
    
    def __unicode__(self):
        return "%s | %s | %s | %s |%s" % (self.uf.num_adm, self.num_org, self.date_debut, self.date_fin, self.statut)
        
    def imprimer(self):
        path = os.path.join('/reports/das/',str(self.id))
        lien = "<a href=%s>%s</a>" % (path,'imprimer')
        return lien
    imprimer.allow_tags=True
    imprimer.short_description='Demande Admission Subventions'
    
    def uf_link(self):
        return '<a href="%s">%s</a>' % (urlresolvers.reverse('admin:formation_uniteformation_change', args=(self.uf.id,)), self.uf)
    uf_link.allow_tags = True
    uf_link.short_description = "Unité de formation"
    uf_link.admin_order_field = "uf__num_adm"

class ActiviteUf(models.Model):
    uf = models.ForeignKey('UniteFormation')
    numero = models.IntegerField()
    categorie = models.CharField(max_length=10)
    libelle = models.CharField(max_length=200)
    periodes = models.IntegerField("Périodes")

    def __unicode__(self):
        return "%s (%s-%s)" % (self.libelle,self.categorie, self.periodes)

class DemandeAdmission(OrganisationUf):

    class Meta:
        proxy = True
        verbose_name = "Demande d'admission"
        verbose_name_plural = "Demandes d'admission"

class DomaineFormation(models.Model):
    code_domaine = models.IntegerField("Code domaine")
    nom_domaine = models.CharField("Domaine", max_length=200)
    
    def __unicode__(self):
        return "%s | %s" % (self.code_domaine, self.nom_domaine)

######################
# Modèles Inspecteur
######################
class Inspecteur(models.Model):
    nom = models.CharField(max_length=50)
    prenom = models.CharField("Prénom", max_length=50)
    email = models.EmailField("E-Mail")
    
    def __unicode__(self):
        return u"%s %s" % (self.nom, self.prenom)
    
    class Meta:
        ordering = ['nom', 'prenom']

NIV_CHOICES = (
              ("TS","Tous"),
              ("SI","SI"),
              ("SS","SS")
              )

class AttributionInspecteur(models.Model):
    prefixe = models.CharField("Préfixe", max_length="4")
    niveau = models.CharField(max_length="2", choices=NIV_CHOICES, default="Tous")
    inspecteur = models.ForeignKey(Inspecteur)
    
    @classmethod
    def get_inspecteur_for_uf(self, uf):
        longest_prefix = str(uf.code)[:4]
        attribution = None
        while len(longest_prefix) > 0:
            try:
                attribution = self.objects.get(prefixe=longest_prefix)
                if attribution.niveau == "TS" or attribution.niveau == uf.niveau:
                    break
                else:
                    attribution = None
                    raise AttributionInspecteur.DoesNotExist
            except AttributionInspecteur.DoesNotExist:
                longest_prefix = longest_prefix[:-1]
        return getattr(attribution, "inspecteur", None)
    
    def __unicode__(self):
        return u"%s\t\t%s\t%s" % (self.prefixe, self.niveau, self.inspecteur)